package com.kangtu.demoweixinpay.config;

import com.kangtu.demoweixinpay.httpclient.WechatPayHttpClientBuilder;
import com.kangtu.demoweixinpay.httpclient.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

/**
 * @program: demo-weix-pay
 * @description: WeiXinConfig
 * @author: 亮子说编程
 * @create: 2021-03-01 15:23
 **/

@Configuration
@Slf4j
public class WeiXinConfig {
    private static String mchId = "1900009191"; // 商户号
    private static String mchSerialNo = "1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C"; // 商户证书序列号

    private CloseableHttpClient httpClient;

    private static String reqdata = "{\n"
            + "    \"stock_id\": \"9433645\",\n"
            + "    \"stock_creator_mchid\": \"1900006511\",\n"
            + "    \"out_request_no\": \"20190522_001中文11\",\n"
            + "    \"appid\": \"wxab8acb865bb1637e\"\n"
            + "}";

    // 你的商户私钥
    private static String privateKey = "-----BEGIN PRIVATE KEY-----\n"
            + "-----END PRIVATE KEY-----";

    // 你的微信支付平台证书
    private static String certificate =  "-----BEGIN CERTIFICATE-----\n"
            + "-----END CERTIFICATE-----";

    public CloseableHttpClient getWeiXinPay() throws IOException {
        log.info("getWeiXinPay() ...");
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                new ByteArrayInputStream(privateKey.getBytes("utf-8")));
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(
                new ByteArrayInputStream(certificate.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        return httpClient;
    }
}
